import React,{useState,useEffect} from 'react'
import './warehouse.css'
import ConvertPinyin from '../page/lang'
import { Space, Table, Tag ,Modal,TreeSelect,Switch, Pagination  } from "antd"
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000'
export default function Warehouse() {
    let [name,setName]=useState('')
    let [code,setCode]=useState('')
    let [department,setDepartment]=useState('')
    let [head, setHead] = useState('')
    let [phone, setPhone] = useState('')
    let [address, setAddress]=useState('')
    let [remark, setRemark]=useState('')
    let [isSwitch, setIsSwitch]=useState(false)
    let [checkId, setCheckId] = useState('')
    let [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = (flag) => {
      console.log(flag)
        if(!flag){
            setName('')
            setCode('')
            setDepartment('')
            setHead('')
            setPhone('')
            setAddress('')
            setRemark('')
            setIsSwitch(false)
            setCheckId('')
        }else{
            let copyObj={...data.filter(item=>item._id == indexArr[0])[0]};
            setName(copyObj.name)
            setCode(copyObj.code)
            setDepartment(copyObj.department)
            setHead(copyObj.head)
            setPhone(copyObj.phone)
            setAddress(copyObj.address)
            setRemark(copyObj.remark)
            setIsSwitch(copyObj.isSwitch)
            setCheckId(copyObj._id)
        }
        setIsModalOpen(true);
      };

      const handleOk =async () => {
        let reg=/^1[3-9]\d{9}$/
        if(!(reg.test(phone))){
            return alert('输入的手机不正确')
        }
        let res=null
        if(checkId){
            res=await axios.put(`/updateList/${checkId}`,{name, code, department, head, phone, address, remark, isSwitch})
        }else{
            res=await axios.post('/addList',{ name, code, department, head, phone, address, remark, isSwitch })
        }
        if(res.data.code == 200){
            setName('')
            setCode('')
            setDepartment('')
            setHead('')
            setPhone('')
            setAddress('')
            setRemark('')
            setIsSwitch(false)
            setIsModalOpen(false);
            setCheckId('')
            getList()
        }
      };
      const handleCancel = () => {
        setIsModalOpen(false);
      };
      const names=(e)=>{
        setName(e.target.value)
        setCode(ConvertPinyin.ConvertPinyin(e.target.value))
      }
      const treeData = [
        {
          value: '河北部门',
          title: '河北部门',
          children: [
            {
              value: '保定部门',
              title: '保定部门',
              children: [
                {
                  value: '莲池区',
                  title: '莲池区',
                },
              ],
            },
          ],
        },
        {
            value:'北京部门',
            title:'北京部门',
            children:[
                {
                    value:'朝阳区',
                    title:'朝阳区',
                    children:[
                        {
                            value:'朝阳区小学',
                            title:'朝阳区小学',
                        },    
                    ]
                }

            ]
        }
      ];

      const onChangeDepartment = (newValue) => {
        setDepartment(newValue);
      };


      let [indexArr, setIndexArr]=useState([''])
      const [page,setPage]=useState(1)
      const [pageSize,setPageSize]=useState(2)
      const [total,setTotal]=useState(0)
      const changeIndex=(a)=>{
        setIndexArr([a[0]])
      }

      let [data,setDate]=useState([])
      let getList=async()=>{
        let data=await axios.get('/getList')
        setDate(data.data.data)
        setIndexArr([data.data.data[0]._id])
        setTotal(data.data.total)
      }
      useEffect(()=>{
        getList()
      },[page,pageSize])

      const del=async()=>{
        if(confirm('确定要删除吗')){
          let res=await axios.delete(`/deleteList/${indexArr[0]}`)
          if(res.data.code == 200){
              getList()
          }
          }
      }
    const columns = [
        {
          title: '序号',
          render:(a,b,c)=>{return <span>{ c + 1 }</span>}
        },
        {
          title: '状态',
          render:(a)=>{
            return <span>{ a.status ? '正常' : '停用' }</span>
          }
        },
        {
          title: '仓库名称',
          dataIndex: 'name',
          filters:data.map(item=>{
            return {text:item.name,value:item.name}
          }),
          onFilter:(value,record)=>record.name.indexOf(value) === 0,
        },
        {
          title: '仓库编码',
          dataIndex: 'code',
          defaultSortOrder: '',
          sorter: (a, b) => a.code.length - b.code.length,
          filters:data.map(item=>{
              return {text:item.code,value:item.code}
          }),
          onFileter:(value,record)=>record.code.indexOf(value) === 0
        },
        {
          title: '所属部门',
          dataIndex: 'department',
        },
        {
          title:'地区',
          dataIndex:'address',
          defaultSortOrder: '',
          sorter: (a, b) => a.address.length - b.address.length,
        },
        {
            title:'是否默认',
            render:(a)=>{
                return <span>{ a.isDefault ? '是' : '否' }</span>
            }
        },
        {
            title:'是否锁定',
            render:(a)=>{
                return <span>{a.isLock ? "已锁定" : "未锁定"}</span>
            }
        }
      ]
  return (
    <div>
        <ul className='top_btn'>
            <li onClick={()=>{showModal()}}>添加</li>
            <li onClick={()=>{showModal('edit')}}>修改</li>
            <li onClick={del}>删除</li>
            <li>查询</li>
            <li>查看</li>
            <li>刷新</li>
            <li>停用</li>
            <li>锁定</li>
            <li>更多</li>
        </ul>
        <div className='top_btn'>
            <span>仓库名称<input type='text'/></span>
        </div>
        <div>
        <Table 
            rowSelection={{
                type:'radio',
                selectedRowKeys:indexArr,
                onChange:changeIndex
            }}
            onChange={(pagination)=>{
                setPage(pagination.current)
                setPageSize(pagination.pageSize)
            }}
            columns={columns} 
            dataSource={data} 
            showSorterTooltip={{
                target:'sorter-icon'
            }}
            pagination={{
                page:page,
                pageSizeOptions:[2,4,6,8],
                pageSize:pageSize,
                showSizeChanger:true,
                total:total,
            }}
        >
        </Table>
        </div>
            <Modal title="创建创库" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <div>
                    <span className='add_span'>创库名称</span>
                    <input className='add_input' type='text' value={name} onChange={(e)=>names(e)} />
                </div>
                <div>
                    <span className='add_span'>助记码</span>
                    <input type='text' className='add_input' value={code}  />
                </div>
                <div style={{ display: 'flex' }}>
                <span className='add_span'>所属部门</span>
                <TreeSelect
                    showSearch
                    style={{
                        width: '100%',
                    }}

                    value={department}
                    dropdownStyle={{
                        maxHeight: 400,
                        overflow: 'auto',
                    }}
                    placeholder="Please select"
                    allowClear
                    treeDefaultExpandAll
                    onChange={onChangeDepartment}
                    treeData={treeData}
                />
                </div>
                <div>
                    <span className='add_span'>负责人</span>
                    <input type='text' className='add_input' value={head} onChange={(e)=>setHead(e.target.value)}/>
                </div>
                <div>
                    <span className='add_span'>联系电话</span>
                    <input type='text' className='add_input' value={phone} onChange={(e)=>setPhone(e.target.value)}/>
                </div>
                <div>
                    <span className='add_span'>地址</span>
                    <input type='text' className='add_input' value={address} onChange={(e)=>setAddress(e.target.value)}/>
                </div>
                <div>
                    <span className='add_span'>备注</span>
                    <input type='text' className='add_input' value={remark} onChange={(e)=>setRemark(e.target.value)}/>
                </div>
                <div>
                    <span className='add_span'>是否默认</span>
                    <Switch checkedChildren="是" unCheckedChildren="否" value={isSwitch} onChange={(e) => { setIsSwitch(e) }} />
                </div>
            </Modal>
    </div>
  )
}
